package com.example.demo.util;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailUtil {
	//发送者邮箱(这里需要自己填写发送邮件的邮箱)
	private static final String SENDADDRESS = "xxxxxx@qq.com";
	//授权码（写入开启邮箱服务时获取到的对应的授权码）
	private static final String POP3_CODE = "xxxxxx";
	private static final String IMAP_CODE = "xxxxxx";
	
	public static void send(String email) {
		try{
			//设置初始化参数
			Properties properties = new Properties();
			//认证邮箱
			properties.put("mail.user", SENDADDRESS);
			//授权码：此处用任何一个授权码都可以
			//采用不同的授权码时邮箱服务器会使用不同的协议发送邮件
			properties.put("mail.password", POP3_CODE);
			//是否认证
			properties.put("mail.smtp.auth", true);
			//协议(认证的协议)
			properties.put("mail.transport.protocol", "smtp");
			//邮箱服务器
			properties.put("mail.stmp.host", "smtp.qq.com");
			//邮箱服务器端口号
			properties.put("maill.smtp.port", "25");
			
			//创建session
			Session session = Session.getDefaultInstance(properties);
			
			//创建消息
			Message message = new MimeMessage(session);
			//发送人
			message.setFrom(new InternetAddress(SENDADDRESS));	
			//收件人
			message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
			//邮件主题(主题可以自己填写自己需要的主题)
			message.setSubject("用户激活邮件-商城注册邮件");
			
			//邮件内容（邮件内容可以自己填写，a标签中的url需要填写自己对应的url）
			String email_content = "<h1>此邮件为蜗牛学院电商平台激活邮件，请点击下面链接完成激活！</h1>"
						+ "<h4><a href='http://localhost:8080/woniumall/user/activation?email='"+email+">"+
						"http://localhost:8080/woniumall/user/activation?email="+email+"</a></h4>";
			//设置字符编码
			message.setContent(email_content, "text/html;charset=UTF-8");
			//保存更改
			message.saveChanges();
			
			//设置协议并链接到服务器
			Transport transport = session.getTransport("smtp");
			transport.connect(
					properties.getProperty("mail.stmp.host"), 
					properties.getProperty("mail.user"), 
					properties.getProperty("mail.password"));
			//发送邮件
			transport.sendMessage(message, message.getAllRecipients());
			//关闭
			transport.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

